<template>
    <div class="out_box">
        <div class="relative content_box">
            <div class="case_box desc_box mb_20" v-if="!hasQuery">
                <h2 class="bold">请选择提现币种</h2>
                <div class="currency_box">
                    <div class="list" v-for="item of currencysList" :key="item.id" @click="toggleCurrencys(item)">
                        <div :class="['img_box pointer', dataForm.currency === item.currency ? 'select' : '']">
                            <img class="img" :src="img_url_appSource + item.logo" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="case_box form_box mb_20">
                <div class="cl">
                    <h2 class="f_l bold">
                        <img class="img mr_10" :src="img_url_appSource + dataForm.logo" />
                        {{ dataForm.currency + dataForm.coinName + (dataForm.currency === 'USDT' ? ' 提现 ERC20' : ' 提现') }}
                    </h2>
                </div>
                <div class="content mt_30">
                    <v-form class="mt_24 mb_24 hide_required" direction="horizontal" ref="dataForm" :model="dataForm" :rules="formRules">
                        <v-form-item class="border" label="提现地址" :label-col="labelCol" :wrapper-col="wrapperCol">
                            <span class="ant-form-text bold">提现到钱包地址</span>
                        </v-form-item>
                        <v-form-item class="border" label="可用余额" :label-col="labelCol" :wrapper-col="wrapperCol">
                            <span class="ant-form-text blue">{{ Number(dataForm.canUseMoney).toFixed(2) + ' ' + dataForm.currency }}</span>
                        </v-form-item>
                        <v-form-item class="border" label="当日提现上限" :label-col="labelCol" :wrapper-col="wrapperCol">
                            <span class="ant-form-text">{{ dataForm.dayUseNumber + ' / ' + dataForm.dailyCeiling + ' ' + dataForm.currency }}</span>
                        </v-form-item>
                        <v-form-item class="border" :label="dataForm.currency + '提币地址'" :label-col="labelCol" :wrapper-col="wrapperCol" prop="address">
                            <v-input class="input f_l" placeholder="提币地址/转账ID" v-model="dataForm.address"></v-input>
                            <span class="forgot f_l ml_20" style="line-height: 18px;">地址薄<br />免验证提现</span>
                            <span class="cl"></span>
                        </v-form-item>
                        <v-form-item class="border" label="地址名称" :label-col="labelCol" :wrapper-col="wrapperCol" v-show="dataForm.addressType === 1">
                            <v-input class="input" placeholder="例如 My address #1 选填" v-model="dataForm.addressName"></v-input>
                            <!-- <span class="forgot f_l ml_20" style="line-height: 18px;" @click="dataForm.addressType = 2">合作方<br />交易所</span>
                            <span class="cl"></span> -->
                            <p class="tips ml_0">提现成功后，系统会记住您的提现地址，以便下次使用；填写“地址名称”可便于您分辨钱包地址。</p>
                        </v-form-item>
                        <v-form-item class="border" label="地址名称" :label-col="labelCol" :wrapper-col="wrapperCol" v-show="dataForm.addressType === 2">
                            <div class="address_box">
                                <div class="options_box cl">
                                    <v-radio class="options" :label="item.id" v-for="item of dataForm.partnerInformation" :key="item.id" @click.native.prevent="toggleAddressInfo(item.id)" v-model="dataForm.addressID">
                                        <div class="icon_box">
                                            <img class="img" :src="img_url_web + item.logo" />
                                        </div>
                                        <span class="text">{{ item.name }}</span>
                                    </v-radio>
                                </div>
                                <div class="button_box mt_20">
                                    <div :class="['button pointer', { 'opacity_filter': dataForm.currentAddressClicked }]" @click="getPartnerInfor">获取账户信息</div>
                                    <div class="qrcode_list" v-show="dataForm.currentAddressInfo.partnerName">
                                        <img class="img mb_4" :src="img_url_web + dataForm.currentAddressInfo.softImage1" />
                                        <p>{{ dataForm.currentAddressInfo.partnerName + '安卓端APP下载' }}</p>
                                    </div>
                                    <div class="qrcode_list" v-show="dataForm.currentAddressInfo.partnerName">
                                        <img class="img mb_4" :src="img_url_web + dataForm.currentAddressInfo.softImage2" />
                                        <p>{{ dataForm.currentAddressInfo.partnerName + '苹果端APP下载' }}</p>
                                    </div>
                                </div>
                                <div class="tips_box cl mt_20">
                                    <p>虎符官网：<span class="link">{{ dataForm.currentAddressInfo.address }}</span></p>
                                    <p>&nbsp;&nbsp;</p>
                                    <p>用户名称：<span class="text">{{ dataForm.currentAddressInfo.account || '请点击获取账户信息按钮' }}</span></p>
                                    <p>首次登录密码：<span class="text">{{ dataForm.currentAddressInfo.password || '请点击获取账户信息按钮' }}</span></p>
                                </div>
                                <div class="tips_box2 mt_20">
                                    提现成功后，请您按照网址提示，登录到相关交易平台，然后使用默认的用户名和首次登录密码，进行下一步操作；为了您的账户安全，请您及时设置或修改您在第三方平台的登录密码和交易密码。如需帮助，请联系第三方平台。
                                </div>
                                <!-- <span class="forgot f_l mt_10" style="line-height: 18px;" @click="dataForm.addressType = 1">手动填写地址</span>
                                <span class="cl"></span> -->
                            </div>
                        </v-form-item>
                        <v-form-item class="border" label="提现数额（币数）" :label-col="labelCol" :wrapper-col="wrapperCol" prop="cnumber">
                            <v-input class="input" placeholder="请输入您的提现数量" v-model="dataForm.cnumber"></v-input>
                            <p class="tips ml_0" style="color:black;">{{ '(最少 ' + dataForm.minimum + ' ' + dataForm.currency + '，一次最多 ' + $numberAddComma(dataForm.maximum) + ' ' + dataForm.currency + ')' }}</p>
                        </v-form-item>
                        <v-form-item class="border" label="矿池费及手续费率" :label-col="labelCol" :wrapper-col="wrapperCol">
                            <span class="ant-form-text bold">{{ '平台收取矿池费率 ' + dataForm.pitRate + '% + ' + dataForm.coinHandlfee + dataForm.currency + ' / 笔' }}</span>
                        </v-form-item>
                        <v-form-item class="border" label="实际到账" :label-col="labelCol" :wrapper-col="wrapperCol">
                            <v-input class="input" placeholder="" v-model="dataForm.payMoney" disabled></v-input>
                            <p class="tips ml_0" style="color:black;">实际到账  ≈ 提现数额 - (提现数额 * 矿池费率) - 手续费/笔</p>
                        </v-form-item>
                        <v-form-item class="border" label="短信验证码" :label-col="labelCol" :wrapper-col="wrapperCol" prop="codeText">
                            <v-input class="input" placeholder="请输入短信验证码" v-model="dataForm.codeText"></v-input>
                            <span :class="{'forgot ml_20': true, 'sent': sendCodeText}" @click="getMessageCode()">{{ sendCodeText || '获取短信验证码'}}</span>
                        </v-form-item>
                        <v-form-item class="border" label="交易密码" :label-col="labelCol" :wrapper-col="wrapperCol" prop="paymentPassword">
                            <v-input class="input" placeholder="请输入交易密码" v-model="dataForm.paymentPassword" type="password"></v-input>
                            <span class="forgot ml_20" @click="jumpForgot()">忘记交易密码？</span>
                        </v-form-item>
                        <v-form-item class="" label=" " :label-col="labelCol" :wrapper-col="wrapperCol">
                            <v-button class="btn" type="primary" size="large" @click.prevent="pushData()">提交提现申请</v-button>
                        </v-form-item>
                    </v-form>
                    <div class="tips_box">
                        <p class="text">提示：在上面的输入框中，输入您要提现的钱包地址和数额，并填写您的验证码。在确认填写无误后，点击“提交提现申请”按钮提交。您的申请将立即或者24小时内被处理。</p>
                    </div>
                </div>
            </div>
            <div class="case_box logs_box gray_table" v-if="userDATA.memberid">
                <div class="cl">
                    <h2 class="f_l bold">最近提现记录</h2>
                </div>
                <div class="content mt_30">
                    <v-data-table :data='getCashData' :currentData='dataCashLog.records' :columns='columnsCashData' stripe :emptyText="not_data">
                        <template slot="th" slot-scope="props">
                            <div class="text_r" v-if="props.column.field === 'statu'">
                                <span>{{ props.title }}</span>
                            </div>
                            <span v-else>{{ props.title }}</span>
                        </template>
                        <template slot="td" slot-scope="props">
                            <div v-if="props.column.field === 'createTime'">
                                <span>{{ props.content[0] }}<br />{{ props.content[1] }}</span>
                            </div>
                            <div class="text_r" v-else-if="props.column.field === 'statu'">{{ props.content }}</div>
                            <span class="break_all" v-else>{{ props.content }}</span>
                        </template>
                    </v-data-table>
                    <div class="pagination_box">
                        <v-pagination @change="changeCashPage" :total="dataCashLog.total" :show-total="showCashTotal" show-quick-jumper></v-pagination>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import { getMessageCode, getPartnerInfor } from '@doapis/user/user.js';
    import { getCurrencys } from '@doapis/currency/currency.js';
    import { getCashApply, getCashLog, getCurrencyRate } from '@doapis/personal/wallet.js';
    import { Base64 } from '@common/base64.min.js';

    let setCount;
    let isPushData = false;

    export default {
        name: "GetCash",
        data: function() {
            const that = this;
            const checkCnumber = function(rule, value, callback) {
                const dataForm = that.dataForm;
                let setCalc = false;

                clearTimeout(setCalc);
                setCalc = setTimeout(function() {
                    let cnumber = Number(dataForm.cnumber);
                    let payMoney = cnumber - cnumber * (dataForm.pitRate / 100) - Number(dataForm.coinHandlfee);
                    if (cnumber > dataForm.canUseMoney) {
                        callback(new Error('您的余额不足！！'));
                    } else if (cnumber > dataForm.dailyCeiling - dataForm.dayUseNumber) {
                        callback(new Error('您的提现数额已超过当日提现上限，请明日再来！！'));
                    } else if (payMoney < 0) {
                        callback(new Error('提现数额必须大于手续费！！'));
                    } else if (cnumber < dataForm.minimum) {
                        cnumber = dataForm.minimum;
                        callback(new Error('最少需要提现' + dataForm.minimum + that.dataForm.currency + '！！'));
                    } else if (cnumber > dataForm.maximum) {
                        cnumber = dataForm.maximum;
                        callback(new Error('提现一次最多' + dataForm.maximum + that.dataForm.currency + '！！'));
                    } else {
                        dataForm.payMoney = payMoney.toFixed(2);
                        callback();
                    }
                }, 700);
            };
            const checkPaymentPassword = function(rule, value, callback) {
                const dataForm = that.dataForm;
                let setCalc = false;

                clearTimeout(setCalc);
                setCalc = setTimeout(function() {
                    if (!$.testPassword(dataForm.paymentPassword)) {
                        callback(new Error('请填写6-16位，由数字和字母组成的交易密码！！'));
                    } else {
                        callback();
                    }
                }, 700);
            };
            return {
                dataForm: {
                    coinName: '',
                    currency: '',
                    logo: '',
                    currencyName: '',
                    currentAddressInfo: {           // 选择合作方的地址后的当前合作方数据
                        password: '',
                        address: '',
                        softImage1: '',
                        softImage2: '',
                        account: ''
                    },
                    currentAddressClicked: false,   // 账户信息是否已经点击
                    canUseMoney: '',                // 可用余额
                    addressName: '',
                    addressID: null,                // 合作方地址ID
                    address: '',
                    addressType: 1,                 // 地址名称（1：手动输入；2：选择合作方）
                    cnumber: '',
                    codeText: '',                   // 用户填写的验证码
                    paymentPassword: '',
                    payMoney: '',
                    value: ''
                },
                currencysList: [],
                hasQuery: false,        // 是否含有参数（用来判断是否通过侧边栏点击进来的）
                dataCashLog: {},
                pageCash: 1,
                sendCodeText: '',       // 验证码倒计时文字
                codeText: '',           // 接口的验证码
                columnsCashData:[
                    { title:"时间", field:'createTime', width: '16%' },
                    { title:"单号", field:'cperiod', width: '16%' },
                    { title:"金额", field:'cnumber', width: '16%' },
                    { title:"提现地址/转账ID", field:'address', width: '28%' },
                    { title:"确认个数", field:'qnumber', width: '10%' },
                    { title:"状态", field:'statu', width: '7%' },
                ],
                labelCol: {
                    span: 6
                },
                wrapperCol: {
                    span: 16
                },
                formRules: {
                    address: [{
                        required: true,
                        message: '请填写提币地址！！'
                    }],
                    codeText: [{
                        required: true,
                        message: '请填写短信验证码！！'
                    }],
                    paymentPassword: [{
                        required: true,
                        message: '请填写交易密码！！'
                    }, {
                        validator: checkPaymentPassword
                    }],
                    cnumber: [{
                        required: true,
                        message: '请填写提现数额！！'
                    }, {
                        validator: checkCnumber
                    }]
                }
            }
        },
        computed: {
            userDATA: function() {
                const userDATA = this.$store.state.userDATA;
                return userDATA;
            }
        },
        methods: {
            getData: function(params) {
                const that = this;
                const dataForm = this.dataForm;
                getCurrencyRate({
                    currency: dataForm.currency,
                    memberid: that.userDATA.memberid
                }).then(function(res) {
                    const data = $.extend(false, dataForm, res.data);
                    that.dataForm = data;
                    that.dataForm.addressID = data.partnerInformation[0].id;
                    that.dataForm.addressType = data.hasteam > 0 ? 2 : 1;
                });
            },
            getCurrencys: function() {
                const that = this;
                getCurrencys().then(function(res) {
                    const data = res.records;
                    that.currencysList = data;

                    that.toggleCurrencys({
                        currency: data[0].currency,
                        remark2: data[0].remark2,
                        logo: data[0].logo
                    });
                });
            },
            toggleCurrencys: function(params) {
                this.dataForm.currency = params.currency;
                this.dataForm.logo = params.logo;
                this.dataForm.currencyName = params.remark2;
                this.getData();
            },
            getCashData: function() {
                const that = this;
                return getCashLog({
                    current: that.pageCash,
                    memberid: that.userDATA.memberid
                }).then(function(res) {
                    res.data.records.forEach(function(item) {
                        let statu;
                        item.createTime = $.$getFormatMD(new Date(item.createTime), true).split(' ');
                        item.cnumber = item.cnumber + ' ' + item.currency;
                        item.qnumber = '暂不显示';

                        switch(item.statu) {
                            case '1': statu = '审批中';break;
                            case '2': statu = '已通过';break;
                            case '3': statu = '驳回';break;
                        };
                        item.statu = statu;
                    });

                    that.dataCashLog = res.data;
                    return { result: res.data.records };
                });
            },
            getPartnerInfor: function() {
                const that = this;
                const dataForm = that.dataForm;

                if (dataForm.currentAddressClicked) return;

                getPartnerInfor({
                    currency: dataForm.currency,
                    id: dataForm.addressID,
                    memberid: that.userDATA.memberid
                }).then(function(res) {
                    that.dataForm.currentAddressInfo = res.data.data;
                    that.dataForm.currentAddressClicked = true;
                });
            },
            pushData: function(type) {
                const that = this;
                const dataForm = this.dataForm;
                let tipsText = '';

                this.$refs.dataForm.validate(function(valid) {
                    if (valid && !isPushData) {
                        if (!that.userDATA.memberid) {
                            tipsText = '获取会员信息失败！！';
                        } else if (dataForm.codeText !== that.codeText) {
                            tipsText = '短信验证码不正确！！';
                        }

                        if (tipsText) {
                            that.$modal.error({
                                title: '操作错误！！',
                                content: tipsText
                            });
                            return;
                        }

                        isPushData = true;
                        getCashApply({
                            data: {
                                payPassword: dataForm.paymentPassword,
                                currency: dataForm.currency,
                                address: dataForm.address,
                                addressName: dataForm.addressType === 1 ? dataForm.addressName : undefined,
                                cnumber: dataForm.cnumber,
                                servicecharge: dataForm.cnumber * (dataForm.pitRate / 100) + Number(dataForm.coinHandlfee),
                                partnerId: dataForm.addressType === 2 ? dataForm.addressID : null,
                                memberid: that.userDATA.memberid,
                                from:'homeWeb'
                            },
                            alertError: true
                        }).then(function(res) {
                            isPushData = false;
                            if (res.success) {
                                that.$modal.success({
                                    title: '操作成功！！',
                                    content: '提交申请成功，请耐心等待审核结果！！',
                                    onOk: function() {
                                        that.$store.commit({
                                            type: 'togglePersonalMenuKEY',
                                            data: { src: 'Wallet' }
                                        });
                                    }
                                });
                            }
                        }).catch(function(err) {
                            isPushData = false;
                        });
                    } else {
                        that.$modal.error({
                            title: '操作错误！！',
                            content: '提交失败，请检查表单内容！！'
                        });
                        return false;
                    }
                });
            },
            // 获取手机验证码
            getMessageCode: function() {
                const that = this;
                const dataForm = that.dataForm;
                if (!that.userDATA.mobileEmail) {
                    that.$modal.error({
                        title: '操作错误！！',
                        content: '获取手机号码失败！！',
                    });
                } else if (!this.sendCodeText) {
                    let countNum = 60;

                    clearInterval(setCount);
                    setCount = setInterval(function() {
                        if (countNum > 0) {
                            that.sendCodeText =  '重新发送' + countNum + '秒';
                            countNum--;
                        } else {
                            clearInterval(setCount);
                            that.sendCodeText = '';
                        }
                    }, 1000);

                    getMessageCode({
                        mobileEmail: that.userDATA[Base64.encode('mobileEmail')]
                    }).then(function(res) {
                        that.codeText = res.data.toString();
                    });
                }
            },
            changeCashPage: function(val) {
                this.pageCash = val;
                this.getCashData();
            },
            showCashTotal: function(val) {
                return '全部' + this.dataCashLog.total + '条';
            },
            toggleAddressInfo: function(val) {
                if(this.dataForm.addressID === val) return;
                this.dataForm.currentAddressInfo = {
                    password: '',
                    address: '',
                    softImage1: '',
                    softImage2: '',
                    account: ''
                };
                this.dataForm.currentAddressClicked = false;
                this.dataForm.addressID = val;
            },
            // 忘记交易密码
            jumpForgot: function() {
                this.$router.push({ path: '/login_register/forgot', query: { type: 2 }});
            },
            $numberAddComma: $.$numberAddComma
        },
        mounted: function() {
            const query = this.$store.state.personalMenuKEY;
            if (query.currency) {
                this.dataForm.coinName = query.coinName;
                this.dataForm.currency = query.currency;
                this.dataForm.logo = query.currency + '.png';
                this.hasQuery = true;               // 是否为其它页面点击跳转的
                this.getData();
            } else {
                // 只有从侧边栏点击才能选择币种
                this.getCurrencys();
            }
        }
    };
</script>

<style lang="less" scoped>
    @import '~@css/root.less';

    .out_box{
        background-color: #eaeaea;
    }
    .content_box{
        .case_box{
            padding: 20px;
            background-color: white;
            h2 .img{
                width: 26px;
                display: inline;
                vertical-align: middle;
            }
        }
        .desc_box{
            padding: 20px;
            .desc{
                margin-top: 10px;
                font-size: 10px;
                color: #999;
            }
            .currency_box{
                .flex_row_wrap;
                padding: 40px 0 20px 0;
                .list{
                    width: 16.66%;
                    margin-bottom: 20px;
                    .img_box{
                        width: 70px;
                        margin: 0 auto;
                        line-height: 70px;
                        border-radius: 8px;
                        text-align: center;
                        border:2px solid white;
                        background-color: #F7F7F7;
                        &.select{
                            color: white;
                            border-color: @theme_color;
                            background-color: white;
                        }
                        .img{
                            width: 60%;
                            display: inline;
                            vertical-align: middle;
                        }
                    }
                }
            }
        }
        .form_box{
            /deep/ label{
                font-size: 13px;
                color: #999;
                vertical-align: text-bottom;
            }
            /deep/ .ant-form-item{
                padding: 30px 0;
                margin-bottom: 0;
                font-size: 14px;
                color: #333;
                &.border{
                    border-bottom: 1px solid #efeff4;
                }
                &.bold label{
                    font-size: 18px;
                    color: #333;
                }
            }
            /deep/ .ant-form-item-label{
                width: 22%;
                padding-left: 20px;
                text-align: left;
            }
            .input{
                width: 440px;
                margin-bottom: 4px;
                border: 2px solid black;
                box-sizing: content-box;
            }
            .blue{
                color: @theme_color;
            }
            .forgot{
                font-size: 10px;
                line-height: 18px;
                color: @theme_color;
                cursor: pointer;
                &.sent{
                    color: #777;
                }
            }
            .tips{
                margin-left: 10px;
                font-size: 13px;
                color: #999;
                vertical-align: middle;
            }
            .btn{
                width: 180px;
                height: 36px;
                text-align: center;
                border-radius: 34px;
                box-sizing: border-box;
                .orange_linear_ellipsis_btn;
            }
            .tips_box{
                padding: 0 20px;
                font-size: 10px;
                color: #999;
            }
            .address_box{
                .options{
                    width: 50%;
                    float: left;
                    margin-right: 0;
                    margin-bottom: 10px;
                    padding-right: 10px;
                    box-sizing: border-box;
                    .icon_box{
                        display: inline-block;
                        width: 44px;
                        height: 44px;
                        line-height: 44px;
                        padding: 0;
                        margin: 0 10px;
                        border: 1px solid #EFEFF4;
                        border-radius: 8px;
                        background-color: white;
                        vertical-align: middle;
                    }
                }
                .button_box{
                    .button{
                        display: inline-block;
                        width: 180px;
                        line-height: 36px;
                        text-align: center;
                        border-radius: 34px;
                        box-sizing: border-box;
                        .theme_linear_ellipsis_btn;
                    }
                    .qrcode_list{
                        display: inline-block;
                        margin-left: 10%;
                        font-size: 10px;
                        vertical-align: middle;
                        .img{
                            width: 44px;
                        }
                    }
                }
                .tips_box{
                    padding: 10px;
                    color: #999;
                    border-radius: 8px;
                    background-color: #F5F5F5;
                    >p{
                        width: 50%;
                        float: left;
                        .text{
                            color: #CCC;
                        }
                        .link{
                            color: @theme_color;
                        }
                    }
                }
                .tips_box2{
                    font-size: 10px;
                    line-height: 16px;
                    color: #999;
                }
            }
        }
        .logs_box{
            padding: 20px 30px;
            /deep/ .ant-table-thead>tr>th{
                color: #999;
                background-color: white;
            }
            .content{
                font-size: 16px;
                margin-bottom: 10px;
                /deep/ .ant-table-tbody>tr>td, /deep/ .ant-table-thead>tr>th{
                    font-size: 13px;
                    font-weight: normal;
                }
            }
        }
    }
</style>
